package com.ruoyi.verify.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


import com.fasterxml.jackson.annotation.JsonView;
import com.ruoyi.verify.domain.*;
import com.ruoyi.verify.mapper.*;
import com.ruoyi.verify.transform.VerifyPlanInfos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.ruoyi.verify.service.IVerifyTemplateService;


import lombok.extern.slf4j.Slf4j;

import com.google.common.base.Joiner;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.redis.annotation.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;




/**
 * 现场审核模板Service业务层处理
 *
 * @author ygx
 * @date 2020-10-14
 */

@Service
@Slf4j
public class VerifyTemplateServiceImpl implements IVerifyTemplateService
{
    @Autowired
    private VerifyTemplateMapper verifyTemplateMapper;
    @Autowired
    private GetContentServiceImpl getContentServiceImpl;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private VerifyLevelMapper verifyLevelMapper;
	@Autowired
	private VerifyTemplateContentMapper verifyTemplateContentMapper;
	@Autowired
	VerifyReportMapper verifyReportMapper;
	@Autowired
	VerifyPlanInfoMapper verifyPlanInfoMapper;
	@Autowired
	VerifyMemberInfoMapper verifyMemberInfoMapper;

	//结果正确
	static final String Ok = "1";
	//新增
	static final String New = "New";
	//发布
	static final String Publish = "Publish";
	//取消
	static final String Cancel = "Cancel";
	//打分临时状态
	static final String Temporary = "Temporary";
	//预览
	static final String Priview = "Priview";
	//大类
	static final String Class = "Class";
	//题目
	static final String Division = "Division";
	//选项
	static final String Section = "Section";
	//读
	static final String Read = "Read";
	//写
	static final String Write = "Write";

    /**
     * 查询现场审核模板
     *
     * @param templateid 现场审核模板ID
     * @return 现场审核模板
     */
    @Override
    public List<VerifyTemplate> selectVerifyTemplateById(String templateid)
    {
        return verifyTemplateMapper.selectVerifyTemplateById(templateid);
    }

    /**
     * 查询现场审核模板列表
     *
     * @param verifyTemplate 现场审核模板
     * @return 现场审核模板
     */
    @SuppressWarnings("unused")
	@Override
    public List<VerifyTemplate> selectVerifyTemplateList(VerifyTemplate verifyTemplate)
    {
		// 拆分状态字符串
    	if (verifyTemplate.getCompanycodelist() != null && verifyTemplate.getCompanycodelist().length > 0)
    	{
    		String companycodelists = "";
    		for (String companycodelist : verifyTemplate.getCompanycodelist())
    		{
    			//拼接sql语句
    			String sql = " FIND_IN_SET(".concat(companycodelist).concat(",companycode) or ");
    			companycodelists = companycodelists.concat(sql);
    		}
    		System.out.print("拼接sql" + companycodelists.substring(0, companycodelists.length() -4));
    		verifyTemplate.setCompanycode(companycodelists.substring(0, companycodelists.length() -4));
    	}
        return verifyTemplateMapper.selectVerifyTemplateList(verifyTemplate);
    }

    /**
     * 新增现场审核模板
     *
     * @param verifyTemplate 现场审核模板  调用来源  ：v 方法  c 控制层 外部调用
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertVerifyTemplate(VerifyTemplate verifyTemplate,String from)
    {
    	String result = Ok;
    	List<String> newcompanycodelist = new ArrayList<String>();
    	String[] companycodelist = verifyTemplate.getCompanycodelist();
    	String[] companynamelist = verifyTemplate.getCompanynamelist();
    	//对数组进行排序
    	Arrays.sort(companycodelist);
    	List<String> checkstatus = new ArrayList<String>();
    	verifyTemplate.setTemplatecode(createContractCode("SH"));
    	for(int i=0;i<companycodelist.length;i++){
			String checkTempCode = verifyTemplateMapper.checkTempCode(companycodelist[i],verifyTemplate.getType(),"");
			if (checkTempCode != null && StringUtils.isNotEmpty(checkTempCode))
			{
				checkstatus.add("模板名称" +verifyTemplate.getTemplatename()
						+ "绑定公司" + companynamelist[i]  + "失败：" + "该公司已存在新增或已发布且类型为" + verifyTemplate.getType() + "的审核模板，"
						+ "请解除老模板的公司绑定，并重新绑定新模板，或废止老模板！");
			}
			else {
				newcompanycodelist.add(companycodelist[i]);
			}
		}
//       	for ( String companycode : companycodelist)
//    	{
//       		String checkTempCode = verifyTemplateMapper.checkTempCode(companycode,verifyTemplate.getType(),"");
//    		if (checkTempCode != null && StringUtils.isNotEmpty(checkTempCode))
//    		{
//    			checkstatus.add("模板编号" + verifyTemplate.getTemplatecode() + "模板名称" +verifyTemplate.getTemplatename()
//    			+ "绑定公司" + companycode  + "失败：" + "该公司已存在新增或已发布且类型为" + verifyTemplate.getType() + "的审核模板，"
//    					+ "已存在的模板号为" + checkTempCode + "请解除老模板的公司绑定，并重新绑定新模板，或废止老模板！");
//    		}
//    		else {
//    			newcompanycodelist.add(companycode);
//			}
//
//    	}

		if (newcompanycodelist != null && newcompanycodelist.size() > 0) {
			Collections.sort(newcompanycodelist);
			verifyTemplate.setCompanycode(Joiner.on(",").join(newcompanycodelist));
			verifyTemplate.setCompanyname(verifyTemplateMapper.selectCompanyName(verifyTemplate.getCompanycode()));
		}
		else
		{
			return Joiner.on(",").join(checkstatus);
		}

		if (checkstatus != null && checkstatus.size() > 0) {
			result = Joiner.on(",").join(checkstatus);
		}


    	boolean checktype = checkType(verifyTemplate.getType());
    	verifyTemplate.setStatus(New);
    	verifyTemplate.setCreateuser(verifyTemplateMapper.selectUserNameById(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID)));
    	verifyTemplate.setCreateuserid(ServletUtils.getRequest().getHeader(Constants.CURRENT_USERNAME));
    	verifyTemplate.setCreatedate(new Date());
    	//假如from为c则为新增，需生成id并在审核模板表新增此条数据。若为v则为修改，只需要生成新的等级和内容
    	if ("c".equals(from))
    	{
    		verifyTemplate.setTemplateid(UUID.randomUUID().toString().replace("-", ""));
        	try {
    			verifyTemplateMapper.insertVerifyTemplate(verifyTemplate);
    		} catch (Exception e) {
    			result = "写入审核模板表失败，请联系管理员！";
    			log.error(result, e);
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			return result;
    		}
        	result = getContentServiceImpl.insertContent(verifyTemplate.getTemplateid(),verifyTemplate.getType());
    	}
    	if ("v".equals(from))
    	{
		result = getContentServiceImpl.insertContent(verifyTemplate.getTemplateid(),verifyTemplate.getType());
    	}
	    if (result != "1")
		{
	    	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return result;
		}
	    //假如新增模板的类型不存在(需要在新数据插入之前查询，数据插入之后刷新)，则代表为新增类型，需刷新redis中的模板类型数据
	    if (!checktype)
	    {
			//删除redis缓存数据，确保下次调用时，可以刷新redis中的模板类型数据
			redisTemplate.delete("verify_template_type:1");
	    }
		if (checkstatus != null && checkstatus.size() > 0 ) {
			result = Joiner.on(",").join(checkstatus);
		}
		if ("1".equals(result))
		{
			result = "id:" + verifyTemplate.getTemplateid();
		}
        return result;
    }

    /**
     * 修改现场审核模板
     *
     * @param verifyTemplate 现场审核模板
     * @return 结果
     */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public String updateVerifyTemplate(VerifyTemplate verifyTemplate)
    {
    	String result = Ok;
    	//判断状态是否是新增，只允许修改新增状态的
    	String templateId = verifyTemplate.getTemplateid();
    	List<String> checkstatus = new ArrayList<String>();
    	List<String> newcompanycodelist = new ArrayList<String>();
    	String[] companycodelist = verifyTemplate.getCompanycodelist();
    	Arrays.sort(companycodelist);
    	if (checkstatus(New, templateId)) {
    		//判断公司字符串是否与原模板公司字符串相等，不相等则需要进行审核模板类型唯一判断
    		if (!verifyTemplateMapper.checkCompanyCode(verifyTemplate.getTemplateid(),Joiner.on(",").join(companycodelist)))
    		{
    	       	for ( String companycode : companycodelist)
    	    	{
    	       		String checkTempCode = verifyTemplateMapper.checkTempCode(companycode,verifyTemplate.getType(),verifyTemplate.getTemplateid());
    	    		if (checkTempCode != null && StringUtils.isNotEmpty(checkTempCode))
    	    		{
    	    			checkstatus.add("模板编号" + verifyTemplate.getTemplatecode() + "模板名称" +verifyTemplate.getTemplatename()
    	    			+ "绑定公司" + companycode  + "失败：" + "该公司已存在新增或已发布且类型为" + verifyTemplate.getType() + "的审核模板，"
    	    					+ "已存在的模板号为" + checkTempCode + "请解除老模板的公司绑定，并重新绑定新模板，或废止老模板！");
    	    		}
    	    		else {
    	    			newcompanycodelist.add(companycode);
    				}

    	    	}

    			if (newcompanycodelist.size() > 0 && newcompanycodelist != null) {
    				verifyTemplate.setCompanycode(Joiner.on(",").join(newcompanycodelist));
    				verifyTemplate.setCompanyname(verifyTemplateMapper.selectCompanyName(verifyTemplate.getCompanycode()));
    			}
    			else
    			{
    				return Joiner.on(",").join(checkstatus);
    			}

    		}
    	//判断模板内容是否与原模板内容相等，不相等则重新获取
    	if (!verifyTemplateMapper.checkContent(templateId,verifyTemplate.getContent()))
    	{
				try {
				    //删除等级、内容，
					verifyLevelMapper.deleteVerifyLevelById(templateId);
					verifyTemplateContentMapper.deleteVerifyTemplateContentById(templateId);
					//更新审核模板表
					verifyTemplateMapper.updateVerifyTemplate(verifyTemplate);
					//从上步更新的数据中取出最新的模板内容，重新生成等级和内容
					insertVerifyTemplate(verifyTemplate,"v");
				} catch (Exception e) {
					result = "审核模板：" + verifyTemplate.getTemplatecode() + ",修改失败，请联系管理员！";
					log.error(result, e);
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return result;
				}
			}
    	else {
    		verifyTemplateMapper.updateVerifyTemplate(verifyTemplate);
		}
    	}
    	else {
    		result = "审核模板：" + verifyTemplate.getTemplatecode() + ",不是新增状态，不允许修改模板内容！";
    		return result;
		}
		if (!checkType(verifyTemplate.getType()))
		{
			//删除redis缓存数据，刷新redis中的模板类型数据
			redisTemplate.delete("verify_template_type:1");
		}
		if (checkstatus.size() > 0 && checkstatus != null) {
			result = Joiner.on(",").join(checkstatus);
		}
        return result;
    }

    /**
	 * 修改现场审核模板状态
	 *
	 * @param VerifyTemplate
	 * @return 结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String updateTemplateStatus(Map<String, List<VerifyTemplate>> datas) {

		String result = Ok;
		List<String> checkstatus = new ArrayList<String>();


		for (VerifyTemplate verifyTemplate : datas.get("datas")) {
			//判断是否允许变更状态
	    	verifyTemplate.setCreateuser(verifyTemplateMapper.selectUserNameById(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID)));
	    	verifyTemplate.setCreateuserid(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
	    	verifyTemplate.setCreatedate(new Date());
		   if ( Publish.equals(verifyTemplate.getStatus()))
		   {
			   if (!checkstatus(New, verifyTemplate.getTemplateid()))
			   {
			   checkstatus.add(verifyTemplate.getTemplatecode() + "不是新增状态，不允许发布！");
			   }
		   else
		   {
			   //更新状态
			   verifyTemplateMapper.updateTemplateStatus(verifyTemplate);
		   }
		}

		   if ( Cancel.equals(verifyTemplate.getStatus()))
		   {
			   if (!checkstatus(Publish, verifyTemplate.getTemplateid()))
			   {
				   checkstatus.add(verifyTemplate.getTemplatecode() + "不是发布状态，不允许废止！");
			   }

		   else
		   {
			   //更新状态
			   verifyTemplateMapper.updateTemplateStatus(verifyTemplate);
		   }
		}

		}
		if (checkstatus.size() > 0 && checkstatus != null) {
			result = Joiner.on(",").join(checkstatus);
		}

			//删除redis缓存数据，确保下次调用时，可以刷新redis中的模板类型数据
			redisTemplate.delete("verify_template_type:1");
		return result;
	}


    /**
     * 删除现场审核模板对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public String deleteVerifyTemplateByIds(String ids)
    {
    	String result = Ok;
		List<String> checkstatus = new ArrayList<String>();
		String[] id = ids.split(",");
		for (String templateId : id) {
			if (checkstatus(New, templateId)) {
				try {
					verifyTemplateMapper.deleteVerifyTemplateById(templateId);
					verifyLevelMapper.deleteVerifyLevelById(templateId);
					verifyTemplateContentMapper.deleteVerifyTemplateContentById(templateId);
				} catch (Exception e) {
					result = "删除审核模板失败,审核模板号" + verifyTemplateMapper.selectTemplateCode(templateId) + ",请联系管理员！";
					log.error(result, e);
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return result;
				}
			} else {
				checkstatus.add(verifyTemplateMapper.selectTemplateCode(templateId));
			}
		}
		if (checkstatus.size() > 0 && checkstatus != null) {
			result = Joiner.on(",").join(checkstatus) + "不是新增状态，不允许删除，已发布的可进行废止！";
		}
		//删除redis缓存数据，刷新redis中的模板类型数据
		redisTemplate.delete("verify_template_type:1");
		return result;
    }

    /**
     * 删除现场审核模板信息
     *
     * @param templateid 现场审核模板ID
     * @return 结果
     */
    public int deleteVerifyTemplateById(String templateid)
    {
        return verifyTemplateMapper.deleteVerifyTemplateById(templateid);
    }

    /**
     * 获取全部的模板类型
     * @return
     */
    @RedisCache(key = "verify_template_type", fieldKey = "1")
    public List<Map<String,String>>  selectType()
    {
    	return verifyTemplateMapper.selectType();
    }

	/**
	 * 通过redis自增生模板号（如：SH202008030001）
	 *
	 * @param prefix 合同号前缀
	 * @return 合同号
	 */
	public String createContractCode(String prefix) {

		String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
		String key = prefix  + datetime;

		// 然后把 时间戳和优化后的 ID 拼接
		String code = null;
		try {
			// 查询 key 是否存在， 不存在返回 1 ，存在的话则自增加1
			Long autoID = redisTemplate.opsForValue().increment(key, 1);
			log.info("获取autoID值：" + autoID);
			// 这里是 4 位id，如果位数不够可以自行修改 ，下面的意思是 得到上面 key 的 值，位数为 4 ，不够的话在左边补 0 ，比如 110 会变成
			// 0110
			String value = StringUtils.leftPad(String.valueOf(autoID), 4, "0");
			code = MessageFormat.format("{0}{1}", key, value);
			// 设置三天过期
			redisTemplate.expire(key, 3, TimeUnit.DAYS);
		} catch (Exception e) {
			log.error("连接redis生成流水号异常！",e);
		}
		return code;
	}

	/**
	 * 检查类型是否存在
	 * @param type
	 * @return
	 */
	public boolean checkType(String type)
	{
		return verifyTemplateMapper.checkType(type);
	}

	/**
	 * 检查类型是否存在
	 * @param type
	 * @return
	 */
	public boolean checkstatus(String status,String templateId)
	{
		return verifyTemplateMapper.checkStatus(status,templateId);
	}

	   /**
     * 通过模板id获取该模板所有模块的名称和id
     *
     * @param
     * @return 结果
     */
	@Override
    public List<Map<String,String>> selectVerifyid(String templateid)
    {
    	return verifyTemplateMapper.selectVerifyid(templateid);
    }


	   /**
    * 通过计划id获取该计划包含的模块id
    *
    * @param
    * @return 结果
     */
    public List<String> selectPlanVerifyid(String planid)
    {
	return verifyTemplateMapper.selectPlanVerifyid(planid,null);
    }
	   /**
  * 通过parentid获取模块id
  *
  * @param
  * @return 结果
  */
    public List<String>  selectVerifyidByParentid(String parentids)
   {
 	return verifyTemplateMapper.selectVerifyidByParentid(parentids);
   }

    /**
    * 通过计划id获取该计划用來生成计划的所有模板id
    *
    * @param
    * @return 结果
    */

	@Transactional(rollbackFor = Exception.class)
    public String  selectVerifyidAllByPlanid(String planid, String loguser)
   {
    	String result = Ok;
    	String divisionVerifyid = null;
    	String sectionVerifyid = null;
    	String classVerifyid = "'".concat(Joiner.on("','").join(verifyTemplateMapper.selectPlanVerifyid(planid,null))).concat("'");
    	if (classVerifyid != null && StringUtils.isNotEmpty(classVerifyid))
    	{
    		divisionVerifyid = "'".concat(Joiner.on("','").join(verifyTemplateMapper.selectVerifyidByParentid(classVerifyid))).concat("'");
    	}
    	else
    	{
    		result = "审核计划" + planid + "参数" + classVerifyid + "未找到题目" + "请联系管理员！";
    		return result;
    	}
    	if (divisionVerifyid != null && StringUtils.isNotEmpty(classVerifyid))
    	{
            sectionVerifyid = "'".concat(Joiner.on("','").join(verifyTemplateMapper.selectVerifyidByParentid(divisionVerifyid))).concat("'");
    	}
    	else
    	{
    		result = "审核计划" + planid + "参数" + divisionVerifyid + "未找到选项" + "请联系管理员！";
    		return result;
    	}
    	return classVerifyid.concat(",").concat(divisionVerifyid).concat(",").concat(sectionVerifyid);
   }

    /**
     * 通过计划的所有verifyid，将数据插入问卷表，生成审核问卷
     *
     * @param
     * @return 结果
     */
	@Override
	@Transactional(rollbackFor = Exception.class)
     public String  insertQuestionnaire(VerifyQuestionnaire verifyQuestionnaire,String factorycode)
    {
    	String result = Ok;
     	String verifyidAll = selectVerifyidAllByPlanid(verifyQuestionnaire.getPlanid(),"");
//     	System.out.print(verifyidAll);
//		List<VerifyTemplate> verifyTemplates = null;
//		List<VerifyTemplate> son_Ep6 = null;
//		List<VerifyTemplate> Ep6 = null;
//		if(verifyQuestionnaire.getVerifytype().contains("VDA6.3")){//VDA6.3中，选中P6则默认选中P6下所有子模块
//			verifyTemplates = verifyTemplateMapper.selectVerifyTemplateClassNew(verifyQuestionnaire.getVerifytype(),factorycode);
//			son_Ep6 = verifyTemplates.stream().filter(v -> v.getContent().startsWith("6.")).collect(Collectors.toList());
//			Ep6 = verifyTemplates.stream().filter(v -> v.getContent().startsWith("6、")).collect(Collectors.toList());
//		}
//
//		if(son_Ep6 !=null && verifyidAll.contains(Ep6.get(0).getVerifyid())){//如果选中了P6模块，则保存P6下的所有子模块
//			List<String> son_Ep6List = son_Ep6.stream().map(s -> "'"+s.getVerifyid()+"'").collect(Collectors.toList());
//			verifyidAll=  StringUtils.join(son_Ep6List,",") +"," + verifyidAll;
//		}
     	if (!StringUtils.isEmpty(verifyidAll) && verifyidAll != null)
     	{
     	if (!verifyidAll.contains("管理员"))
     	{
     		verifyQuestionnaire.setStatus(New);
     		verifyQuestionnaire.setCreateuser(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
     		verifyQuestionnaire.setCreatedate(new Date());
     		verifyQuestionnaire.setVerifyid(verifyidAll);
     		verifyTemplateContentMapper.insertQuestionnaire(verifyQuestionnaire);
     	}
     	else
     	{
     		return verifyidAll;
     	}
     	}
     	else
     	{
     		result = "根据计划生成问卷失败，请联系管理员！";
     	}
     	return result;
    }

     /**
      * 通过计划的模板id，将数据插入问卷表，生成审核问卷
      *
      * @param
      * @return 结果
      */
	@Override
	@Transactional(rollbackFor = Exception.class)
     public List<Object>  selectQuestionnaire(String templateid,String verifytype)
     {
     	//删除以前的问卷预览
     	verifyTemplateContentMapper.deletePriviewContentById(templateid);
     	VerifyQuestionnaire verifyQuestionnaire = new VerifyQuestionnaire();
      		verifyQuestionnaire.setStatus(Priview);
      		verifyQuestionnaire.setCreateuser("0");
      		verifyQuestionnaire.setMemo("问卷预览");
      		verifyQuestionnaire.setCompanycode("0");
      		verifyQuestionnaire.setCreatedate(new Date());
      		verifyQuestionnaire.setTemplateid(templateid);
		 verifyQuestionnaire.setVerifytype(verifytype);
      		//插入新的问卷预览
      		verifyTemplateContentMapper.insertQuestionnaire(verifyQuestionnaire);
      		//生成问卷
      		verifyQuestionnaire.setContent(verifyTemplateMapper.selectTemplateNameByTemplateid(verifyQuestionnaire.getTemplateid()));
      	return selectQuestionnaireClass(verifyQuestionnaire);
     }


	/**
     * 通过计划的计划id，获取审核问卷
     *
     * @param
     * @return 结果
     */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public List<Object>  selectQuestionnaire(VerifyQuestionnaire verifyQuestionnaire)
    {
		if (verifyQuestionnaire.getParentid() == null)
		{
			verifyQuestionnaire.setParentid("-1");
		}
		verifyQuestionnaire.setContent(verifyTemplateMapper.selectTemplateNameByPlanid(verifyQuestionnaire.getPlanid()));
     	return selectQuestionnaireClass(verifyQuestionnaire);
    }


	/**
	 * 通过计划的计划id，获取审核问卷（全）
	 *
	 * @param
	 * @return 结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public List<Object>  selectAllQuestionnaire(VerifyQuestionnaire verifyQuestionnaire)
	{
		if (verifyQuestionnaire.getParentid() == null)
		{
			verifyQuestionnaire.setParentid("-1");
		}
		verifyQuestionnaire.setContent(verifyTemplateMapper.selectTemplateNameByPlanid(verifyQuestionnaire.getPlanid()));
		verifyQuestionnaire.setType(Class);

		LinkedHashMap<String,Object> resultMap = new LinkedHashMap<String,Object>();
		List<Object> resultList = new ArrayList<Object>();
		List<Object> list = new ArrayList<Object>();
		List<LinkedHashMap<String,Object>> classContents = new ArrayList<>();

		//查询分数，因为VDA6.3每道题不需要写分数，和原逻辑冲突，需单独操作
		classContents = verifyTemplateContentMapper.selectAllVdaQuestionnaireContent(verifyQuestionnaire);
		for (Map<String,Object> classContent : classContents)
		{
			verifyQuestionnaire.setVerifyid(classContent.get("verifyid").toString());
			classContent.put("question", selectQuestionnaireDivision(verifyQuestionnaire));
			classContent.put("title", classContent.remove("content"));
			classContent.remove("verifyid");
			list.add(classContent);
		}
		resultMap.put("title", verifyQuestionnaire.getContent());
		resultMap.put("moduleList", list);
		resultList.add(resultMap);
		return resultList;
	}


     /**
      * 生成审核问卷(大类)
      *
      * @param VerifyQuestionnaire
      * @return 结果
      */


	public List<Object> selectQuestionnaireClass(VerifyQuestionnaire verifyQuestionnaire)
     {
    	 verifyQuestionnaire.setType(Class);
    	 LinkedHashMap<String,Object> resultMap = new LinkedHashMap<String,Object>();
    	 List<Object> resultList = new ArrayList<Object>();
    	 List<Object> list = new ArrayList<Object>();
		 List<LinkedHashMap<String,Object>> classContents = new ArrayList<>();
    	 verifyQuestionnaire.setLoguser(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
		 //查询分数，因为VDA6.3每道题不需要写分数，和原逻辑冲突，需单独操作
		 if(verifyQuestionnaire.getVerifytype()!=null && verifyQuestionnaire.getVerifytype().contains("VDA6.3")){
			 classContents = verifyTemplateContentMapper.selectVdaQuestionnaireContent(verifyQuestionnaire);
		 }else{
			 classContents = verifyTemplateContentMapper.selectQuestionnaireContent(verifyQuestionnaire);
		 }
    	 for (Map<String,Object> classContent : classContents)
    	 {
    		 verifyQuestionnaire.setVerifyid(classContent.get("verifyid").toString());
    		 classContent.put("question", selectQuestionnaireDivision(verifyQuestionnaire));
    		 classContent.put("title", classContent.remove("content"));
    		 classContent.remove("verifyid");
    		 list.add(classContent);
    	 }
    	 resultMap.put("title", verifyQuestionnaire.getContent());
    	 resultMap.put("moduleList", list);
    	 resultList.add(resultMap);
    	 return resultList;
     }

     /**
      * 生成审核问卷(题目)
      *
      * @param
      * @return 结果
      */


	public List<Object> selectQuestionnaireDivision(VerifyQuestionnaire verifyQuestionnaire)
     {
    	 verifyQuestionnaire.setType(Division);
    	 List<Object> list = new ArrayList<Object>();
		 List<LinkedHashMap<String,Object>> divisionContents = new ArrayList<>();
    	 if(verifyQuestionnaire.getVerifytype().contains("VDA6.3")){
			 divisionContents = verifyTemplateContentMapper.selectVdaQuestionnaireContent(verifyQuestionnaire);
		 }else{
			 divisionContents = verifyTemplateContentMapper.selectQuestionnaireContent(verifyQuestionnaire);

		 }
    	 for (LinkedHashMap<String,Object> divisionContent : divisionContents)
    	 {
    		verifyQuestionnaire.setVerifyid(divisionContent.get("verifyid").toString());
    		divisionContent.put("option", selectQuestionnaireSection(verifyQuestionnaire));
    		divisionContent.put("title", divisionContent.remove("content"));
    		if (Publish.equals(divisionContent.get("status")) || Priview.equals(divisionContent.get("status")))
    		{
    			divisionContent.put("operation", Read);
    		}
    		else if (New.equals(divisionContent.get("status")))
    		{
    			divisionContent.put("operation", Write);
    		}
    		else {
    			//三元表达式判断，如果有修改权限则为write 否则为read
    			divisionContent.put("operation",verifyTemplateContentMapper.checkUpdateAuth(divisionContent.get("questionnaireid").toString(),
    					ServletUtils.getRequest().getHeader(Constants.CURRENT_ID)) ? Write : Read);
			}
    		divisionContent.remove("verifyid");
    		divisionContent.remove("status");
    		list.add(divisionContent);
    	 }
    	 return list;
     }

//	public List<Object> selectAllQuestionnaireDivision(VerifyQuestionnaire verifyQuestionnaire)
//	{
//		verifyQuestionnaire.setType(Division);
//		List<Object> list = new ArrayList<Object>();
//		List<LinkedHashMap<String,Object>> divisionContents = new ArrayList<>();
//
//		divisionContents = verifyTemplateContentMapper.selectAllVdaQuestionnaireContent(verifyQuestionnaire);
//
//		for (LinkedHashMap<String,Object> divisionContent : divisionContents)
//		{
//			verifyQuestionnaire.setVerifyid(divisionContent.get("verifyid").toString());
//			divisionContent.put("option", selectQuestionnaireSection(verifyQuestionnaire));
//			divisionContent.put("title", divisionContent.remove("content"));
//			if (Publish.equals(divisionContent.get("status")) || Priview.equals(divisionContent.get("status")))
//			{
//				divisionContent.put("operation", Read);
//			}
//			else if (New.equals(divisionContent.get("status")))
//			{
//				divisionContent.put("operation", Write);
//			}
//			else {
//				//三元表达式判断，如果有修改权限则为write 否则为read
//				divisionContent.put("operation",verifyTemplateContentMapper.checkUpdateAuth(divisionContent.get("questionnaireid").toString(),
//						ServletUtils.getRequest().getHeader(Constants.CURRENT_ID)) ? Write : Read);
//			}
//			divisionContent.remove("verifyid");
//			divisionContent.remove("status");
//			list.add(divisionContent);
//		}
//		return list;
//	}

     /**
      * 生成审核问卷(选项)
      * @param VerifyQuestionnaire
      * @return 结果
      */
	public LinkedHashMap<String,Object> selectQuestionnaireSection(VerifyQuestionnaire verifyQuestionnaire)
     {
    	 verifyQuestionnaire.setType(Section);
    	 LinkedHashMap<String,Object> m = new LinkedHashMap<String,Object>();
		 List<LinkedHashMap<String,Object>> SectionContents = new ArrayList<>();
		 if(verifyQuestionnaire.getVerifytype()!=null && verifyQuestionnaire.getVerifytype().contains("VDA6.3")){
			 SectionContents = verifyTemplateContentMapper.selectVdaQuestionnaireContent(verifyQuestionnaire);
		 }else{
			 SectionContents = verifyTemplateContentMapper.selectQuestionnaireContent(verifyQuestionnaire);
		 }
    	 for (int i = 0; i < SectionContents.size() ; i++)
    	 {
    		 //替换map的key
    		 m.put("option" + (i + 1), SectionContents.get(i).get("content"));
    	 }
    	 return m;
     }

    /**
     * 根据问卷id更新问卷打分、打分人、备注、状态
     * @param verifyTemplateContent
     * @return
     */
	@Override
    public String updateQuestionnaire(Map<String, List<VerifyQuestionnaire>> datas)
    {

    	String result = Ok;
    	List<String> checkstatus = new ArrayList<>();
		for (VerifyQuestionnaire verifyQuestionnaire : datas.get("datas")) {
			//判断是否允许变更状态
			boolean Write = verifyTemplateContentMapper.checkUpdateAuth(verifyQuestionnaire.getQuestionnaireid(),
					ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
			String status = verifyTemplateContentMapper.selectStatusByQuestionnaireid(verifyQuestionnaire.getQuestionnaireid());
    		if (New.equals(status) || (Temporary.equals(status) && Write))
    	  {
			verifyQuestionnaire.setLogusername(verifyTemplateMapper.selectUserNameById(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID)));
			verifyQuestionnaire.setLoguser(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
			verifyQuestionnaire.setLogdate(new Date());
			verifyQuestionnaire.setStatus(Temporary);
			try {
				verifyTemplateContentMapper.updateQuestionnaire(verifyQuestionnaire);
			} catch (Exception e) {
				result = verifyQuestionnaire.getQuestionnaireid() + "打分失败，请联系管理员！";
				log.error(result,e);
				return result;
			}
		}
    		else
    		{
    			checkstatus.add(verifyQuestionnaire.getQuestionnaireid() + verifyQuestionnaire.getContent() + "已有人员打分，不允许他人再次打分！");
    		}
		}

		if (checkstatus.size() > 0 && checkstatus!= null)
		{
			result = Joiner.on(",").join(checkstatus);
		}

		return result;
    }

	/**
	 * 提交问卷
	 * @param 计划id：planid
	 * @param 供应商code ：vendorcode   供应商名称
	 * @param
	 * @return 结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String commitQuestionnaire(VerifyQuestionnaire verifyQuestionnaire)
	{
		String result = Ok;
		verifyQuestionnaire.setLoguser(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
		if (verifyReportMapper.checkCommitExists(verifyQuestionnaire.getPlanid(),verifyQuestionnaire.getVendorname()))
		{
			result = "该问卷已提交过，禁止重复提交！";
		    return result;
		}
		verifyQuestionnaire.setStatus(New);
		verifyQuestionnaire.setType(Division);
		//检查是否包含新增的题目（未作答的）
		if (verifyTemplateContentMapper.checkCommit(verifyQuestionnaire))//此判断正确性待检验--20210128
		{
			result = "有未打分的题目，不允许提交！";
		    return result;
		}
		VerifyPlanInfo verifyplan0 = verifyPlanInfoMapper.selectVerifyPlanInfoById(Long.valueOf(verifyQuestionnaire.getPlanid()));
		if(verifyplan0.getVerifytype().contains("VDA6.3") && verifyTemplateContentMapper.checkIfProblemNull(verifyQuestionnaire)){
			result = "有未填写的问题项，不允许提交！";
			return result;
		}

		else
		{
			// 根据计划、供应商、打分人，更新问卷表相关数据状态为publish。  并计算题目的总分
			// 取消责任人和模块关系时，判断模块是否还有责任人，如果没有，则同步删除问卷表中已产生的模块，否则会造成，问卷无法完成
			List<String> classLists  = verifyTemplateMapper.selectPlanVerifyid(verifyQuestionnaire.getPlanid(),verifyQuestionnaire.getLoguser());

			if (classLists.size()> 0  && classLists != null)
    	{   String classVerifyid = "'".concat(Joiner.on("','").join(classLists).concat("'"));
    		verifyQuestionnaire.setStatus(Publish);
    		String divisionVerifyid = "'".concat(Joiner.on("','").join(verifyTemplateMapper.selectVerifyidByParentid(classVerifyid))).concat("'");
    		verifyQuestionnaire.setVerifyid(divisionVerifyid);
    		verifyTemplateContentMapper.updateQuestionnaire(verifyQuestionnaire);
    	}

		}
		// 将审核人设置为null，判断当该问卷，题目的所有状态均为publish，更新问卷所有内容为publish，计划表状态为publish。并计算问卷的总分、权重和等级写入结果表
		verifyQuestionnaire.setLoguser(null);
		verifyQuestionnaire.setStatus(Publish);
		verifyQuestionnaire.setType(Division);

		boolean b = verifyTemplateContentMapper.checkPublicCommit(verifyQuestionnaire);
		if (!b)
		{
			List<String> classLists  = verifyTemplateMapper.selectPlanVerifyid(verifyQuestionnaire.getPlanid(),verifyQuestionnaire.getLoguser());
			String verifyidAll = selectVerifyidAllByPlanid(verifyQuestionnaire.getPlanid(),verifyQuestionnaire.getLoguser());
			verifyQuestionnaire.setVerifyid(verifyidAll);
			verifyTemplateContentMapper.updateQuestionnaire(verifyQuestionnaire);

    		for (String classList : classLists)
    		{
    			//提交时，更新class的grade、Loguser
        		verifyQuestionnaire.setLoguser(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
        		verifyQuestionnaire.setLogdate(new Date());
        		verifyQuestionnaire.setLogusername(verifyTemplateMapper.selectUserNameById(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID)));
    			String classGrade = verifyTemplateContentMapper.sumByParentId(classList,verifyQuestionnaire.getPlanid(),verifyQuestionnaire.getVendorname());
    			verifyQuestionnaire.setGrade(classGrade);
    			verifyQuestionnaire.setVerifyid("'".concat(classList).concat("'"));
    			verifyTemplateContentMapper.updateQuestionnaire(verifyQuestionnaire);
    		}

    		//计算等级和总分并写入结果表


			if(verifyplan0.getVerifytype().contains("VDA6.3")){
				insetVdaResult(verifyQuestionnaire);
			}else{
				insetResult(verifyQuestionnaire);
			}



    		//如果所有模块都完成，改变子计划状态
//			List<VerifyPlanInfo> verifyPlanInfos = verifyPlanInfoMapper.selectVerifyPlanInfoByParentId(Long.valueOf(verifyQuestionnaire.getPlanid()));
//			List<VerifyPlanInfo> collect = verifyPlanInfos.stream().filter(vpi -> vpi.getSuppliername().equals(verifyQuestionnaire.getVendorcode())).collect(Collectors.toList());
			VerifyPlanInfo verifyPlanInfo = new VerifyPlanInfo();
//			verifyPlanInfo.setPlanid(collect.get(0).getPlanid());
			verifyPlanInfo.setPlanid(Long.valueOf(verifyQuestionnaire.getPlanid()));
			verifyPlanInfo.setGlobalcommit(1l);
			verifyPlanInfoMapper.updateVerifyPlanInfo(verifyPlanInfo);
		}
		return result;
	}

	/**
	 * VDA6.3审核计算结果
	 */
	public void insetVdaResult(VerifyQuestionnaire verifyQuestionnaire)
	{
		double sumGrade = 0;
		double sumScore = 0;
		String currentQuestionLevel = "A";
		String degradeStatus = "";

		double Ep6_grade=0;
		double Ep6_actualscore=0;
		Map<String,String> degradedStatusList = new HashMap<>();
		degradedStatusList.put("1","A");//计算总的eg
		degradedStatusList.put("2","A");//只要有一个星号问题评分为4分则降级。只要有一个星号问题评分为0分，降为C级。
		degradedStatusList.put("3","A");//不允许有评分为0的问题，否则降级
		degradedStatusList.put("4","A");//只要Eu1-Eu7符合程度小于80%则降级
		degradedStatusList.put("5","A");//只要Ep2-Ep7符合程度小于80%则降级，小于70则评为C级
//		degradedStatusList.put("6","A");

//		String currentClassLevel = "A";
//		String templateid = verifyTemplateMapper.selectTemplateidByPlanid(verifyQuestionnaire.getPlanid());
//		String templateName = verifyTemplateMapper.selectTemplateNameByPlanid(verifyQuestionnaire.getPlanid());
		verifyQuestionnaire.setVerifyid("'".concat(Joiner.on("','").join(verifyTemplateMapper.selectPlanVerifyid(verifyQuestionnaire.getPlanid(),null)).concat("'")));
		List<LinkedHashMap<String, String>> resultLists = verifyTemplateContentMapper.selectResult(verifyQuestionnaire).stream().filter(v ->!v.get("content").startsWith("6、")).collect(Collectors.toList());
		for (LinkedHashMap<String, String> resultList : resultLists)
		{
			double grade = Double.parseDouble(resultList.get("grade"));


//			double score = Double.parseDouble(resultList.get("score"));//VDA审核中的模块总分需要去除不适用的题目

			String verifyid = resultList.get("verifyid");
			String content = resultList.get("content");

			List<VerifyQuestionnaire> verifyQuestionnaires = verifyTemplateContentMapper.selectVdaContentByVerifyid(verifyid, verifyQuestionnaire.getPlanid());
//			long unsuitablenumbers = verifyQuestionnaires.stream().filter(vq -> vq.getIfsuitable().equals("unsuitable")).count();
			long suitablenumbers = verifyQuestionnaires.stream().filter(vq -> vq.getIfsuitable().equals("suitable")).count();

			//若果题目全部不适用，则跳过此模块。
			if(suitablenumbers==0){
				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"A");
				continue;
			}
			double actualscore = suitablenumbers*10;
			double eg = 0;
			if(actualscore!=0){
				eg = new BigDecimal(grade/actualscore*100).setScale(0, RoundingMode.HALF_UP).doubleValue();
			}
//			//只要Eu1-Eu7符合程度小于80%则为B级
//			if(content.startsWith("6.")){
//				Ep6_grade+=grade;
//				Ep6_actualscore+=actualscore;
//				if(eg>=80){
//					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"A");
//					degradedStatusList=CalculationStatusList(degradedStatusList,"4","A");
//				}else{
//					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
//					degradedStatusList=CalculationStatusList(degradedStatusList,"4","B");
//				}
//			}else{//只要Ep2-Ep7符合程度小于80%则为B级，小于70则评为C级
//				if(eg>=80){
//					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"A");
//					degradedStatusList=CalculationStatusList(degradedStatusList,"5","A");
//				}else if(eg>=70){
//					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
//					degradedStatusList=CalculationStatusList(degradedStatusList,"5","B");
//				}else{
//					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"C");
//					degradedStatusList=CalculationStatusList(degradedStatusList,"5","C");
//				}
//			}
			//只要Eu1-Eu7符合程度小于80%则为B级
			if(content.startsWith("6.")){
				Ep6_grade+=grade;
				Ep6_actualscore+=actualscore;
				if(eg>=80){
					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"A");
					degradedStatusList=CalculationStatusList(degradedStatusList,"4","A");
				}else{
//					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
					degradedStatusList=CalculationStatusList(degradedStatusList,"4","down");
				}
			}else{//只要Ep2-Ep7符合程度小于80%则为B级，小于70则评为C级
				if(eg>=80){
					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"A");
					degradedStatusList=CalculationStatusList(degradedStatusList,"5","A");
				}else if(eg>=70){
//					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
					degradedStatusList=CalculationStatusList(degradedStatusList,"5","down");
				}else{
					currentQuestionLevel=CalculationGrade(currentQuestionLevel,"C");
					degradedStatusList=CalculationStatusList(degradedStatusList,"5","C");
				}
			}



			VerifyQuestionnaire classVerifyQuestionnaire = new VerifyQuestionnaire();
			classVerifyQuestionnaire.setEg(String.valueOf(eg));
			classVerifyQuestionnaire.setActualscore(String.valueOf(actualscore));
//			classVerifyQuestionnaire.setPlanid(verifyQuestionnaire.getPlanid());
//			classVerifyQuestionnaire.setVdalevel(currentClassLevel);
			classVerifyQuestionnaire.setVerifyid("'"+verifyid+"'");
			verifyTemplateContentMapper.updateQuestionnaire(classVerifyQuestionnaire);

			//只要有一个星号问题评分为4分，降为B级。只要有一个星号问题评分为0分，降为C级。
			long levelB = verifyQuestionnaires.stream().filter(vq -> vq.getIfsuitable().equals("suitable") && vq.getAsterisk().equals("1") && (vq.getGrade().equals("2") || vq.getGrade().equals("4"))).count();
			if(levelB>0){
//				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
				degradedStatusList=CalculationStatusList(degradedStatusList,"2","down");
			}
			long levelC = verifyQuestionnaires.stream().filter(vq -> vq.getIfsuitable().equals("suitable") && vq.getAsterisk().equals("1") && (vq.getGrade().equals("0"))).count();
			if(levelC>0){
//				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"C");
				degradedStatusList=CalculationStatusList(degradedStatusList,"2","down");
			}

			//不允许有评分为0的问题，否则评为B
			long zeroNumbers = verifyQuestionnaires.stream().filter(vq -> vq.getIfsuitable().equals("suitable")  && (vq.getGrade().equals("0"))).count();
			if(zeroNumbers>0){
//				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
				degradedStatusList=CalculationStatusList(degradedStatusList,"3","down");
			}

			sumGrade += grade;//整个问卷的实际得分
			sumScore += actualscore;//整个问卷是实际总分
		}
		//循环结束后，判断Ep6的eg。小于80%则为B级，小于70则评为C级
		if(Ep6_grade!=0 && Ep6_actualscore!=0){
			double Ep6_eg = Ep6_grade/Ep6_actualscore*100;
			if(Ep6_eg>80){
				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"A");
			}else if(Ep6_eg>=70){
//				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
				degradedStatusList=CalculationStatusList(degradedStatusList,"5","down");
			}else{
				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"C");
				degradedStatusList=CalculationStatusList(degradedStatusList,"5","C");
			}
		}

		//计算总的eg
		double totaleg = sumGrade / sumScore*100;
		Set<Map.Entry<String, String>> entries = degradedStatusList.entrySet();

		List<Map.Entry<String, String>> down = entries.stream().filter(e -> e.getValue().equals("down")).collect(Collectors.toList());

		if(totaleg>=90){
			currentQuestionLevel=CalculationGrade(currentQuestionLevel,"A");
			if(down !=null && down.size()!=0){
				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
				for (Map.Entry<String, String> d : down) {
					degradedStatusList.put(d.getKey(),"B");
				}
			}
		}else if(totaleg>=80){
			currentQuestionLevel=CalculationGrade(currentQuestionLevel,"B");
			degradedStatusList=CalculationStatusList(degradedStatusList,"1","B");
			if(down !=null && down.size()!=0){
				currentQuestionLevel=CalculationGrade(currentQuestionLevel,"C");
				for (Map.Entry<String, String> d : down) {
					degradedStatusList.put(d.getKey(),"C");
				}
			}
		}else{
			currentQuestionLevel=CalculationGrade(currentQuestionLevel,"C");
			degradedStatusList=CalculationStatusList(degradedStatusList,"1","C");
			if(down !=null && down.size()!=0){
				for (Map.Entry<String, String> d : down) {
					degradedStatusList.put(d.getKey(),"C");
				}
			}
		}
//		degradedStatusList=CalculationStatusList(degradedStatusList,"6",currentQuestionLevel);

		Set<Map.Entry<String,String>> ens = degradedStatusList.entrySet();
		for(Map.Entry<String,String> e:ens){//此处是否乱序，有待验证
			degradeStatus+=e.getValue()+",";
		}
		degradeStatus+=currentQuestionLevel;

		//保留两位小数，四舍五入
		sumScore = new BigDecimal(sumScore).setScale(2, RoundingMode.HALF_UP).doubleValue();
		sumGrade = new BigDecimal(sumGrade).setScale(2, RoundingMode.HALF_UP).doubleValue();
		totaleg = new BigDecimal(totaleg).setScale(0, RoundingMode.HALF_UP).doubleValue();
		VerifyReport verifyReport = new VerifyReport();
		verifyReport.setCreateuserid(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
		verifyReport.setCreatedate(new Date());
		verifyReport.setPlanid(verifyQuestionnaire.getPlanid());
		verifyReport.setVendorcode(verifyQuestionnaire.getVendorcode());
		verifyReport.setVendorname(verifyQuestionnaire.getVendorname());
		verifyReport.setScore(String.valueOf(sumGrade));//问卷实际得分
		verifyReport.setActualscore(String.valueOf(sumScore));//问卷实际总分
		verifyReport.setLevel(currentQuestionLevel);
		verifyReport.setTotaleg(String.valueOf((int)totaleg));
		verifyReport.setDegradeStatus(degradeStatus);
		verifyReportMapper.insertVerifyReport(verifyReport);
	}



	/**
	 * 根据计划id和供应商code将结果插入report表
	 * @param planid vendorcode
	 * @return
	 */
	public String insetResult(VerifyQuestionnaire verifyQuestionnaire)
	{
		String result = Ok;
		double sumScore = 0;
		String templateid = verifyTemplateMapper.selectTemplateidByPlanid(verifyQuestionnaire.getPlanid());
		String templateName = verifyTemplateMapper.selectTemplateNameByPlanid(verifyQuestionnaire.getPlanid());
		verifyQuestionnaire.setVerifyid("'".concat(Joiner.on("','").join(verifyTemplateMapper.selectPlanVerifyid(verifyQuestionnaire.getPlanid(),null)).concat("'")));
		List<LinkedHashMap<String, String>> resultLists = verifyTemplateContentMapper.selectResult(verifyQuestionnaire);
		for (LinkedHashMap<String, String> resultList : resultLists)
		{
		 	double grade = Double.parseDouble(resultList.get("grade"));
		 	double score = Double.parseDouble(resultList.get("score"));
		 	double weight = Double.parseDouble(resultList.get("weight"));
		 	//打分除以总分乘以权重
		 	double count = grade/score*weight;

		 	sumScore += count;
		}
		//保留两位小数，四舍五入
		sumScore = new BigDecimal(sumScore).setScale(2, RoundingMode.HALF_UP).doubleValue();
		VerifyReport verifyReport = new VerifyReport();
		verifyReport.setCreateuserid(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
		verifyReport.setCreatedate(new Date());
		verifyReport.setPlanid(verifyQuestionnaire.getPlanid());
		verifyReport.setVendorcode(verifyQuestionnaire.getVendorcode());
		verifyReport.setVendorname(verifyQuestionnaire.getVendorname());
		verifyReport.setScore(String.valueOf(sumScore));
		verifyReport.setLevel(getlevelResult(sumScore,templateid,verifyQuestionnaire.getPlanid(),verifyQuestionnaire.getVendorname(),templateName));
		verifyReportMapper.insertVerifyReport(verifyReport);
		return result;
	}


	/**
	 * 根据计划id和供应商code获取问卷结果
	 * @param planid
	 * @return
	 */
	@Override
	public LinkedHashMap<String, Object> selectResult(VerifyQuestionnaire verifyQuestionnaire)
	{
		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();
		verifyQuestionnaire.setVerifyid("'".concat(Joiner.on("','").join(verifyTemplateMapper.selectPlanVerifyid(verifyQuestionnaire.getPlanid(),null)).concat("'")));
		List<LinkedHashMap<String, String>> resultLists = verifyTemplateContentMapper.selectResult(verifyQuestionnaire);
		resultMap.put("titleList",resultLists);
		VerifyReport verifyReport = new VerifyReport();
		verifyReport.setPlanid(verifyQuestionnaire.getPlanid());
		verifyReport.setVendorcode(verifyQuestionnaire.getVendorcode());
		verifyReport.setVendorname(verifyQuestionnaire.getVendorname());
		HashMap<String, Object> reportMap = verifyReportMapper.selectVerifyReport(verifyReport);

		Object fileidobject = null;
		if(reportMap!=null && reportMap.containsKey("fileid")){
			fileidobject = reportMap.get("fileid");
		}
		String fileid="";
		if(fileidobject!=null){
			fileid=fileidobject.toString();
		}
		if(StringUtils.isNotEmpty(fileid)){
			String[] fileidlist = fileid.split(",");
			resultMap.put("fileidlist",fileidlist);
		}

		VerifyPlanInfo vpi = verifyPlanInfoMapper.selectVerifyPlanInfoById(Long.valueOf(verifyQuestionnaire.getPlanid()));

		//获取供货类别
		if (vpi.getSupplycategory() != null) {
			resultMap.put("supplycategory",vpi.getSupplycategory().split(","));
		}

		//成员信息
		List<VerifyPlanInfos.innerVerify> vpmm = selectVerifyMemberInfoByPlanid(vpi);

		resultMap.put("vpmm",vpmm);
		resultMap.putAll(reportMap);
		resultMap.put("problemList",verifyReportMapper.selectProblemById(String.valueOf(reportMap.get("reportid"))));
		Long memberid = Long.valueOf(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
		resultMap.put("operation",verifyPlanInfoMapper.isgroupleader(memberid,Long.valueOf(verifyQuestionnaire.getPlanid()))==true?"Writed":"Read");
		return resultMap;
	}

	@Override
	public LinkedHashMap<String, Object> selectVdaResult(VerifyQuestionnaire verifyQuestionnaire) {
		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();
		verifyQuestionnaire.setVerifyid("'".concat(Joiner.on("','").join(verifyTemplateMapper.selectPlanVerifyid(verifyQuestionnaire.getPlanid(),null)).concat("'")));
		//去除P6的子模块
		List<LinkedHashMap<String, String>> resultLists = verifyTemplateContentMapper.selectResult(verifyQuestionnaire).stream().filter(v -> !v.get("content").startsWith("6.")).collect(Collectors.toList());
		List<String> header = resultLists.stream().map(r -> r.get("content").substring(0,1)).collect(Collectors.toList());
		String verifyMoudles = "P" + StringUtils.join(header, "、P");
//		resultMap.put("titleList",resultLists);
		resultMap.put("verifyMoudles",verifyMoudles);

		VerifyPlanInfo vpi = verifyPlanInfoMapper.selectVerifyPlanInfoById(Long.valueOf(verifyQuestionnaire.getPlanid()));


		VerifyReport verifyReport = new VerifyReport();
		verifyReport.setPlanid(verifyQuestionnaire.getPlanid());
		verifyReport.setVendorcode(verifyQuestionnaire.getVendorcode());
		verifyReport.setVendorname(verifyQuestionnaire.getVendorname());
		HashMap<String, Object> reportMap = verifyReportMapper.selectVerifyReport(verifyReport);

		if(reportMap.get("degradeStatus")!=null && StringUtils.isNotEmpty(reportMap.get("degradeStatus").toString())){
			String[] split = reportMap.get("degradeStatus").toString().split(",");
			resultMap.put("degradeStatusList",split);
		}

		Object fileidobject = null;
		if(reportMap!=null && reportMap.containsKey("fileid")){
			fileidobject = reportMap.get("fileid");
		}
		String fileid="";
		if(fileidobject!=null){
			fileid=fileidobject.toString();
		}
		if(StringUtils.isNotEmpty(fileid)){
			String[] fileidlist = fileid.split(",");
			resultMap.put("fileidlist",fileidlist);
		}

		//获取供货类别
		if (vpi.getSupplycategory() != null) {
			resultMap.put("supplycategory",vpi.getSupplycategory().split(","));
		}


		//成员信息
		List<VerifyPlanInfos.innerVerify> vpmm = selectVerifyMemberInfoByPlanid(vpi);

		resultMap.put("scorelist",getVdaScoreList(verifyQuestionnaire.getPlanid()));
		resultMap.put("vpmm",vpmm);

		resultMap.putAll(reportMap);
		resultMap.put("problemList",verifyReportMapper.selectProblemById(String.valueOf(reportMap.get("reportid"))));
		Long memberid = Long.valueOf(ServletUtils.getRequest().getHeader(Constants.CURRENT_ID));
		resultMap.put("operation",verifyPlanInfoMapper.isgroupleader(memberid,Long.valueOf(verifyQuestionnaire.getPlanid()))==true?"Writed":"Read");
		return resultMap;
	}

	/**
	 * 返回成员信息
	 */
	//返回成员信息
	public List<VerifyPlanInfos.innerVerify> selectVerifyMemberInfoByPlanid(VerifyPlanInfo vpi) {
		List<VerifyMemberInfo> verifyMemberInfos = verifyMemberInfoMapper.selectVerifyMemberInfoByPlanid(vpi.getPlanid());
		List<VerifyPlanInfos.innerVerify> vpmm = verifyMemberInfos.stream().map(vmi -> {
			List<String> moudles = Arrays.asList(vmi.getMoudlecode().split(","));
			List<String> moudlenames = Arrays.asList(vmi.getMoudlename().split(","));
			List<VerifyTemplate> verifyTemplates = null;
			List<VerifyTemplate> son_Ep6 = null;
			List<VerifyTemplate> Ep6 = null;

			//VDA6.3 删除P6的子模块列表
			if(vpi.getVerifytype().contains("VDA6.3")){
				verifyTemplates = verifyTemplateMapper.selectHistoryVerifyTemplateClassByPlanid(vpi.getPlanid());
				son_Ep6 = verifyTemplates.stream().filter(v -> v.getContent().startsWith("6.")).collect(Collectors.toList());
				List<String> ep6_verify_list = son_Ep6.stream().map(s -> s.getVerifyid()).collect(Collectors.toList());
				String ep6_string_list = StringUtils.join(ep6_verify_list, ",");
				Ep6 = verifyTemplates.stream().filter(v -> v.getContent().startsWith("6、")).collect(Collectors.toList());

				if(Ep6!=null && Ep6.size()>0){
					if(vmi.getMoudlecode().contains(Ep6.get(0).getVerifyid())){
						moudles = moudles.stream().filter(m -> !ep6_string_list.contains(m)).collect(Collectors.toList());
						moudlenames = moudlenames.stream().filter(m -> !m.startsWith("6.")).collect(Collectors.toList());
					}
				}

			}

			if (vpi.getGroupleaderid() != null) {
				if (vpi.getGroupleaderid().equals(vmi.getMemberid())) {
					vmi.setIsGroupLeader("1");
				} else {
					vmi.setIsGroupLeader("0");
				}
			}
			VerifyPlanInfos.innerVerify innerVerify = new VerifyPlanInfos.innerVerify(vmi.getPlanid(), vmi.getMemberid(), moudles, vmi.getMembername(), vmi.getPhonenumber(), vmi.getJobnumber(), vmi.getJobunit(), vmi.getPosition(), vmi.getIsGroupLeader());
			innerVerify.setMoudlenames(moudlenames);
			return innerVerify;
		}).collect(Collectors.toList());
		return vpmm;
	}

	/**
	 * 获取所有题目明细
	 */
	public List<VdaResult> getVdaScoreList(String planid){
		List<VerifyQuestionnaire> verifyQuestionnaires = verifyTemplateContentMapper.selectPlanVerifyidAndContent(planid);
		List<VerifyQuestionnaire> verifyQuestionnaireList = verifyQuestionnaires.stream().filter(v -> !v.getContent().startsWith("6、")).collect(Collectors.toList());

		List<VdaResult> vdaResultList = verifyQuestionnaireList.stream().map(v -> {
			List<VerifyQuestionnaire> items = verifyTemplateContentMapper.selectVdaResultbyParentid(v.getVerifyid(),planid);
			VdaResult vdaResult = new VdaResult();
//			int maxValuation = 0;
			vdaResult.setTitle(v.getContent());
			vdaResult.setEvaluation(v.getGrade());
			vdaResult.setHighestevaluation(v.getActualscore());

			if (StringUtils.isEmpty(v.getActualscore())) {
				vdaResult.setCongruence("不适用");
			} else {
				vdaResult.setCongruence(v.getEg());
			}
			Pattern p = Pattern.compile("^([0-9]+(\\u002E[0-9]+)+(\\*)*)"); //取出题目号，后续在解析模板时将题目号存入数据库
			List<VdaResult.items> itemlist = items.stream().map(i -> {
				VdaResult.items item = new VdaResult.items();
				Matcher m = p.matcher(i.getContent());
				while (m.find()) {
					item.setQuestion(m.group(0));
				}
				if (i.getIfsuitable().equals("unsuitable")) {
					item.setScore("不适用");
				} else {
					item.setScore(i.getGrade());
				}
				return item;
			}).collect(Collectors.toList());
			//最高分数暂不提供
			vdaResult.setItems(itemlist);
			return vdaResult;
		}).collect(Collectors.toList());

		return vdaResultList;
	}


	/**
	 * 根据总分、考核单号获取考核等级
	 *
	 * @param sumscore
	 * @param checkcode
	 * @return
	 */
	public String getlevelResult(Double sumScore, String templateid, String planid, String vendorname ,String templateName) {
		String level = null;
		//等级模板分数范围为 100-90 89-80 造成89.1-89.9分无对应等级，故获取等级时，总数去掉小数点后面的小数位
		Double sumscorelevel = Double.valueOf(String.valueOf(sumScore.longValue()));
		//判断分数中是否存在-999分，存在则直接为最低等级
		if (verifyTemplateContentMapper.checkLowLevel(planid,vendorname))
		{   level = verifyTemplateMapper.selectLowerLevel(templateid);
			return level;
		}
		if (sumscorelevel < 0)
		{
			sumscorelevel = 0.0;
		}
		if (sumscorelevel > 100)
		{
			sumscorelevel = 100.0;
		}
		//通过模板id获取模板的等级
		List<HashMap<String, String>> results = verifyTemplateMapper.selectLevel(templateid);
		for (HashMap<String, String> result : results) {
			if (sumscorelevel >= Long.valueOf(result.get("lowerscore")) && sumscorelevel <= Long.valueOf(result.get("upperscore"))) {
				level = result.get("level");
				if (StringUtils.isBlank(level) || level == null) {
					String error = "审核模板" + templateName + " id:" + templateid + "总分为" + sumscorelevel + "无该分值对应的绩效等级，请联系管理员！";
					log.error(error);
					return error;
				}
				else
				{
					return level;
				}
			}
		}
		String error = "审核模板" + templateName + " id:" + templateid + "总分为" + sumScore + "无该分值对应的分值区间，请联系管理员！";
		log.error(error);
		return error;
	}


	@Override
	public List<VerifyTemplate> selectVerifyTemplateClass(String templateid) {
		return verifyTemplateMapper.selectVerifyTemplateClass(templateid);
	}

	@Override
	public List<VerifyTemplate> selectVerifyTemplateClassNew(String verifytype, String factorycode) {
		return verifyTemplateMapper.selectVerifyTemplateClassNew(verifytype,factorycode);
	}

	@Override
	public List<VerifyTemplate> selectHistoryVerifyTemplateClassByPlanid(Long planid) {
		return verifyTemplateMapper.selectHistoryVerifyTemplateClassByPlanid(planid);
	}

	public String CalculationGrade(String currentLevel,String targetLevel){
		String level = "";
		switch (currentLevel){
			case "A":
				level = targetLevel;
				break;
			case "B":
				if(targetLevel.equals("A")){
					level = currentLevel;
				}else{
					level = targetLevel;
				}
				break;
			case "C":
				level = currentLevel;
				break;
			default :
				level = "未知等级";
		}
		return level;
	}

	public Map<String, String> CalculationStatusList(Map<String,String> map, String key, String targetLevel){
		Map<String,String> newmap = map;
		switch (map.get(key)){
			case "A":
				newmap.put(key,targetLevel);
				break;
			case "B":
				if(targetLevel.equals("A")){
					break;
				}else{
					newmap.put(key,targetLevel);
				}
				break;
			case "C":
				break;
		}
		return newmap;
	}

}
